<template>
  <a-spin :spinning='loading'>
    <div class='flex-container'>
      <div class='item item1'>
        <a-card>
          <a-form-model
            ref='formRef'
            :label-col='{ span: 6 }'
            :model='form'
            :wrapper-col='{ span: 14 }'
            @keyup.enter='loadData'
          >
            <a-form-model-item label='物料名称（品名）' prop='materialName'>
              <a-input-search
                v-model:value='form.materialName'
                enter-button
                placehodler='请输入物料名称（品名）'
                @search='loadData'
              />
            </a-form-model-item>
          </a-form-model>
          <a-table
            :columns='columns'
            :dataSource='dataSource'
            :loading='tableLoading'
            :pagination='ipagination'
            :rowSelection='{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }'
            :scroll='{ x: true }'
            rowKey='id'
            size='middle'
            @change='handleTableChange'
          >
          </a-table>
        </a-card>
      </div>
      <div class='item item2'>
        <a-space align='center' direction='vertical' size='large' style='width: 100%;height: 100%'>
          <a-button icon='right' size='large' @click='selectRecords'></a-button>
          <a-button icon='left' size='large' @click='deleteRecords'></a-button>
        </a-space>
      </div>
      <div class='item item3'>
        <a-card>
          <a-space direction='vertical'>
            <slot name='action'></slot>
            <a-table
              :columns='addColumns'
              :dataSource='selectedData'
              :pagination='selectedIpagination'
              :rowSelection='{ selectedRowKeys: selectedDataRowKeys, onChange: onSelectedDataChange }'
              :scroll='{ x: true }'
              rowKey='id'
              @change='handleSelectedTableChange'
            >
              <template slot='number' slot-scope='text, record'>
                <a-input-number v-if='editable' v-model:value='record.number'
                                @change='handleNumberChange($event,record)'></a-input-number>
                <span v-else>{{ text }}</span>
              </template>
              <template slot='perNumber' slot-scope='text, record'>
                <a-input-number v-if=' editable' v-model:value='record.perNumber'
                                @change='handlePerNumberChange($event,record)'></a-input-number>
                <span v-else>{{ text }}</span>
              </template>
              <template slot='remainder' slot-scope='text, record'>
                <a-input-number v-if=' editable' v-model:value='record.remainder' :max='record.perNumber-1' :min='0'
                                @change='handleRemainderChange($event,record)'></a-input-number>
                <span v-else>{{ text }}</span>
              </template>
            </a-table>
          </a-space>
        </a-card>
      </div>
    </div>
  </a-spin>
</template>

<script>
import HfMaterialSearchSelectTag from '@comp/HfManual/HfMaterialSearchSelectTag.vue'
import { downloadFile, getAction, postAction } from '@api/manage'

export default {
  name: 'OutboundCodeList',
  components: { HfMaterialSearchSelectTag },
  watch: {
    selectedData(val) {
      this.$emit('change', val)
    }
  },
  data() {
    // this.loadData = debounce(this.loadData, 1200) //消抖
    return {
      loading: false,
      form: {
        materialName: ''
      },
      tableLoading: false,
      editable: false,
      ipagination: {
        pageSize: 10,
        current: 1,
        total: 0,
        showTotal: (total, range) => `共 ${total} 条`,
        position: 'top'
      },
      selectedIpagination: {
        pageSize: 10,
        current: 1,
        total: 0,
        showTotal: (total, range) => `共 ${total} 条`,
        position: 'top'
      },
      dataSource: [],
      selectedData: [],
      selectedRowKeys: [],
      selectedDataRowKeys: [],
      selectedDataRows: [],
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 20,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '物料名称（品名）',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },

        {
          title: '单箱数',
          align: 'center',
          dataIndex: 'perNumber'
        },
        {
          title: '客户',
          align: 'center',
          dataIndex: 'customId_dictText',
          width: 100
        },
        {
          title: '客户品番',
          align: 'center',
          dataIndex: 'saleCode',
          width: 100
        },
        {
          title: '简号',
          align: 'center',
          dataIndex: 'saleCode1',
          width: 100
        },
        {
          title: 'QAD',
          align: 'center',
          dataIndex: 'qad',
          width: 100
        },
      ],
      addColumns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 20,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '物料名称（品名）',
          align: 'center',
          dataIndex: 'materialName',
          width: 200
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '客户',
          align: 'center',
          dataIndex: 'customId_dictText',
          width: 100
        },
        {
          title: '总数',
          align: 'center',
          dataIndex: 'totalNumber',
          customRender: function(t, r, index) {
            return r.number * r.perNumber + r.remainder
          }
        },
        {
          title: '箱数',
          align: 'center',
          dataIndex: 'number',
          scopedSlots: { customRender: 'number' }
        },
        {
          title: '单箱数',
          align: 'center',
          dataIndex: 'perNumber',
          scopedSlots: { customRender: 'perNumber' }
        },
        {
          title: '余数',
          align: 'center',
          dataIndex: 'remainder',
          scopedSlots: { customRender: 'remainder' }
        }
      ],
      url: {
        list: '/sale/hfSalePrice/codePrintList',
        batchGenerateCode: {
          '100x80': '/label/generateBatchBarcode',
          '2x2': '/label/generateBatchBarcodeA4Large',
          '2x3': '/label/generateBatchBarcodeA4Small'
        }
      }
    }
  },
  computed: {
    existDataIds() {
      return this.selectedData.map(item => item.id)
    }
  },
  methods: {
    loadData() {
      this.tableLoading = true
      getAction(this.url.list, {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        materialName: this.form.materialName
      })
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total
          }
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onSelectedDataChange(selectedRowKeys, selectionRows) {
      this.selectedDataRowKeys = selectedRowKeys
      this.selectedDataRows = selectionRows
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleSelectedTableChange(pagination, filters, sorter) {
      this.selectedIpagination = pagination
    },
    selectRecords() {
      // 如果已存在就跳过
      let filter = this.selectionRows.filter(item => !this.existDataIds.includes(item.id))
      filter.forEach(item => {
        // 创建一个新的响应式对象，而不是直接使用 item
        const newItem = { ...item, number: 1, remainder: 0 }// 浅拷贝 + 初始化 number
        newItem.totalNumber = newItem.number * newItem.perNumber + newItem.remainder
        this.selectedData.push(newItem) // Vue 能检测到数组的 push 操作
      })
      this.onSelectChange([], [])
    },
    deleteRecords() {
      this.selectedData = this.selectedData.filter(item => !this.selectedDataRowKeys.includes(item.id))
      this.onSelectedDataChange([], [])
    },
    edit() {
      if (this.selectedData.length === 0) {
        this.$message.warn('请先选择物料')
        return false
      }

      this.editable = true
      return true
    },
    save() {
      if (this.selectedData.some(item => item.perNumber === 0)) {
        this.$message.error('单箱数不能为0')
        return true
      }
      this.editable = false
      return false
    },
    handleReset() {
      this.selectedData = []
    },
    handleGenerate(type) {
      this.loading = true
      if (this.selectedData.length === 0) {
        this.$message.error('请先选择物料')
        return
      }

      const form = this.selectedData.map(item => {
        item.code = item.saleCode
        item.code1 = item.saleCode1
        item.movementType = 'output'
        item.name = item.customId_dictText
        // item.date = dayjs().format('YYYY-MM-DD')
        return item
      })
      const url = this.url.batchGenerateCode[type]

      postAction(url, form, { timeout: 0 })
        .then(res => {
          if (res.success) {
            downloadFile(res.result.url, `${res.result.pdfName}`)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleNumberChange(value, record) {
      console.log('handleNumberChange', record, value)
      console.log('value', value)
      record.number = value
      record.totalNumber = value * record.perNumber + record.remainder
    },
    handlePerNumberChange(value, record) {
      record.perNumber = value
      record.totalNumber = value * record.number + record.remainder
    },
    handleRemainderChange(value, record) {
      if (value > record.perNumber) {
        this.$message.error('余数不能大于单箱数')
        return
      }
      record.remainder = value
      record.totalNumber = record.perNumber * record.number + value
    }
  }
}
</script>

<style scoped>
.flex-container {
  display: flex; /* 启用 Flexbox */
  width: 100%; /* 容器宽度占满父级 */
  height: 100%;
  justify-content: center;
  //align-items: center;
}

.item {
  height: 100%; /* 统一高度，可根据需要调整 */
}

.item1,
.item3 {
  flex: 6; /* 占2份 */
}

.item2 {
  flex: 1; /* 占1份 */
}

</style>
